import axios from 'axios';

console.log(import.meta.env);
const service = axios.create({
  baseURL: import.meta.env.VITE_SERVER_URL, // url = base url + request url
  timeout: 5000, // request timeout
});

// request 拦截器
service.interceptors.request.use(
  config => {
    // 设置authorization
    config.headers['Authorization'] = 'Bearer ' + sessionStorage.getItem('token');
    return config;
  },
  error => {
    Promise.reject(error);
  }
);

// 响应器
service.interceptors.response.use(response => {
  console.log(response);
  const { authorization } = response.headers || {};

  // 若token 存在，则添加到sessionStorage
  if (authorization) {
    sessionStorage.setItem('token', authorization);
  }

  return response.data;
});

export default service;
